package com.onenine.app.fragment;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Looper;
import android.os.MessageQueue;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.onenine.app.R;
import com.onenine.app.event.AskCoterieEvent;
import com.onenine.app.model.CoterieItem;
import com.onenine.app.utils.DataType;
import com.onenine.base.base.BaseFragment;
import com.onenine.base.view.NiceImageView;
import com.onenine.common.util.ApUtils;
import com.onenine.glide.GlideApp;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

public class CRecommendFragment extends BaseFragment implements ViewPager.OnPageChangeListener {

    private ViewPager mViewPager;
    private CoterieItem mSelectCoterie;
    private List<CoterieItem> mCoterieList = new ArrayList<>();
    private TabLayout mTabLayout;
    private int mPrePosition = -1;
    private static final int UNSELECT_ALPHA = 0x47;
    private static final int SELECT_ALPHA = 0xff;

    @Override
    protected void initView(View view) {
        mViewPager = view.findViewById(R.id.vp_pager);
        mViewPager.addOnPageChangeListener(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_comm_rec;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    /**
     * 绑定数据
     *
     * @param tabLayout
     * @param coterieItemList
     */
    public void bindData(TabLayout tabLayout, List<CoterieItem> coterieItemList) {
        mTabLayout = tabLayout;
        String[] titles = new String[coterieItemList.size()];
        for (int i = 0; i < coterieItemList.size(); i++) {
            CoterieItem coterie = coterieItemList.get(i);
            titles[i] = coterie.getCoterieName();
            if (coterie.getCoterieType() == DataType.COTERIE_ASK) {
                EventBus.getDefault().post(new AskCoterieEvent(coterie.getCoteriePkId()));
            }
        }
        if (mCoterieList != null && !mCoterieList.isEmpty()) {
            mCoterieList.clear();
        }
        mCoterieList.addAll(coterieItemList);
        Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
            @Override
            public boolean queueIdle() {
                mViewPager.setAdapter(new CRecommendFragment.CFragmentAdapter(getChildFragmentManager()));
                tabLayout.setupWithViewPager(mViewPager);
                tabLayout.removeAllTabs();
                for (CoterieItem item : coterieItemList) {
                    tabLayout.addTab(tabLayout.newTab().setCustomView(makeTabView(item)));
                }
                return false;
            }
        });
    }

    /**
     * 引入布局设置图标和标题
     *
     * @return
     */
    private View makeTabView(CoterieItem item) {
        View tabView = LayoutInflater.from(ApUtils.getApp())
                .inflate(R.layout.layout_community_tab_custom_view, null, false);
        TextView textView = tabView.findViewById(R.id.tv_title);
        NiceImageView nImageView = tabView.findViewById(R.id.iv_icon);
        textView.setText(item.getCoterieName());
        if (item.getCoterieType() > 0) {
            //在线圈子
            GlideApp.with(CRecommendFragment.this).load(item.getCoterieIcon())
                    .into(new SimpleTarget<Drawable>() {
                        @Override
                        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                            if (resource != null) {
                                nImageView.setImageDrawable(resource);
                                nImageView.setAlpha(UNSELECT_ALPHA);
                            }
                        }
                    });
        } else {
            //全部
            mSelectCoterie = item;
            mPrePosition = 0;
            setSelectedBorderStyle(nImageView);
        }
        return tabView;
    }

    @Override
    public void onPageSelected(int position) {
        mSelectCoterie = mCoterieList.get(position);
        EventBus.getDefault().post(mSelectCoterie);
        ((CommunityFragment) getParentFragment())
                .changeTopBarBackground(mSelectCoterie);
        if (mTabLayout != null) {
            if (mPrePosition != -1) {
                setCoterieStyle(mPrePosition, false);
            }
            setCoterieStyle(position, true);
            mPrePosition = position;
        }
    }

    /**
     * 设置圈子style
     *
     * @param position
     * @param isSelect
     */
    private void setCoterieStyle(int position, boolean isSelect) {
        View view = mTabLayout.getTabAt(position).getCustomView();
        NiceImageView nImageView = view.findViewById(R.id.iv_icon);
        if (isSelect) {
            nImageView.setAlpha(SELECT_ALPHA);
            setSelectedBorderStyle(nImageView);
            view.setSelected(true);
        } else {
            nImageView.setAlpha(UNSELECT_ALPHA);
            nImageView.setBorderWidth(0);
            view.setSelected(false);
        }
    }

    /**
     * 设置选中样式
     *
     * @param imageView
     */
    private void setSelectedBorderStyle(NiceImageView imageView) {
        imageView.setInnerBorderWidth(1);
        imageView.setInnerBorderColor(Color.WHITE);
        imageView.setBorderWidth(2);
        imageView.setBorderColor(ActivityCompat
                .getColor(ApUtils.getApp(), R.color.d4d2f8));
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private class CFragmentAdapter extends FragmentStatePagerAdapter {

        public CFragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mCoterieList.size();
        }

        @Override
        public Fragment getItem(int position) {
            return CRecListFragment.newInstance(mCoterieList.get(position));
        }
    }

}
